package khiem.data.worldbank;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;

import khiem.data.worldbank.pojo.Source;
import khiem.data.worldbank.pojo.Topic;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class SimpleQuery<T> {
  
  private static final String sourcesURL = "http://api.worldbank.org/sources?format=json";
  private static final String topicsURL = "http://api.worldbank.org/topics?format=json";
  
  public Collection<T> query(String requestURL, TypeToken<Collection<T>> tt) throws IOException {
    URL url = new URL(requestURL);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();

    StringBuilder result = new StringBuilder();
    Reader reader = new InputStreamReader(is);
    int c;
    while ((c=reader.read()) != -1) {
      char ch = (char) c;
      result.append(ch);
    }
    reader.close();
    
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(result.toString());
    JsonArray array = element.getAsJsonArray();
    JsonObject info = array.get(0).getAsJsonObject();
    JsonElement jsonEle = array.get(1);
    Collection<T> output = gson.fromJson(jsonEle, tt.getType());
    for (T s : output) {
      System.out.println(s.toString());
    }
    return output;
  }
  
  public static void main(String[] args) throws IOException {
    System.out.println("SOURCES: ");
    new SimpleQuery<Source>().query(sourcesURL, new TypeToken<Collection<Source>>(){});
    System.out.println("TOPICS: ");
    new SimpleQuery<Topic>().query(topicsURL,  new TypeToken<Collection<Topic>>(){});
  }

}
